

import GameUtil from "./GameUtil";


export default class JsbUtil {
    static setAndroidBackInterceptor2(arg0: () => boolean) {
    }
    static downloadProgress: any;
    static downloadCallback: (percent: any) => void;
    static onRestart: any;
    static sendTj(arg0: number, arg1: string) {
        
    }
    
    public static isAndroid = cc.sys.platform == cc.sys.ANDROID;
    public static isAndrid = cc.sys.platform == cc.sys.ANDROID;
    public static androidJavaPath = "org.cocos2dx.javascript.CocosHelp";
    public static callback = null;
    public static targrt = null;
    public static interceptorCallback = null;
    public static interceptor2Callback = null;
    public static adSwitch = true;

    static init() {
        var self = this;
        
        if (!cc.addGold) {
            cc.addGold = function (gold) {
                UserInfo.addGold(gold)
            }
        }

        if (!cc.onBackPressed) {
            cc.onBackPressed = function () {
                self.backFunction();
            };
        }

        this.androidJavaPath = "org.cocos2dx.javascript.CocosHelp";
    }
    static setOnRestart(callback){
        JsbUtil.onRestart = callback;
        if(!cc.onRestart){
            cc.onRestart = function(key){
                if(JsbUtil.onRestart){
                    Log("onRestart 存在，开始回调")
                    JsbUtil.onRestart(key);
                }else{
                    Log("onRestart 不存在，中止回调")
                }
            };
        }
    }
    static appStar(){
        if (this.isAndroid) {
            JsbUtil.log('申请评分');
            jsb.reflection.callStaticMethod(this.androidJavaPath, 
                "appStar3", 
                "()V");
        }
    }
    static download(str, callback?){
        if (this.isAndroid) {
            var info = JSON.stringify(str);
            console.log('下载文件 info = ',info);
            if(callback){
                this.downloadCallback = callback;
            }
            jsb.reflection.callStaticMethod(this.androidJavaPath, "download", "(Ljava/lang/String;)V",info);
            var self = this;
            cc.downloadCallback = function(porgress){
                if(self.downloadCallback){
                    self.downloadCallback(porgress);
                }else{
                    console.log("下载回调不存在："+porgress);
                }
            }
        }
    }
    static setAndroidWakeJson(str){
        if (this.isAndroid) {
            // console.log('传参拉传参啦 str = ',str)
            jsb.reflection.callStaticMethod(this.androidJavaPath, "initAwakenAd", "(Ljava/lang/String;)V",str);
        }
    }
    static getAndroidAdName(){
        if (this.isAndroid) {
            // console.log('传参拉传参啦 str = ',str)
            return jsb.reflection.callStaticMethod(this.androidJavaPath, "getAndroidAdType", "()Ljava/lang/String;");
        }
    }
    /**
     * 将广告配置信息传给Android做初始化
     * @param str
     */
    static setAndroidAdJson(str){
        if (this.isAndroid) {
            Log('传参拉传参啦 str = ',str)
            jsb.reflection.callStaticMethod(this.androidJavaPath, "initAdConfig", "(Ljava/lang/String;)V",str);
        }
    }
    static awakenAd(back){
        if (this.isAndroid) {
            // console.log('传参拉传参啦 str = ',str)
            cc.awakenAdCallback  = function (str) {
                back && back(str);
            }
            jsb.reflection.callStaticMethod(this.androidJavaPath, "awakenAd", "()V");
        }
        else{
            back && back('true');
        }

    }
    static checkInstall(packname){
        if(this.isAndroid){
            return jsb.reflection.callStaticMethod(this.androidJavaPath, 
                "checkInstall", 
                "(Ljava/lang/String;)Z", packname);
        }
        else
        {
            return false;
        }
    }
    public static getInfo(){
        if(this.isAndroid){
            var info = jsb.reflection.callStaticMethod(this.androidJavaPath, "getStudyInfo", "()Ljava/lang/String;");
            this.upDateComplete();
            return info;
        }else{
            var info:any = {
                "eatTime":1, // 吃饲料的时间 minute
                "food":300, // 增加的饲料
                "getLimit":30, // 礼包解锁所需时间 minute
                "normalTime":30, // 正常状态持续时间 minute
                "studyTime":2400000, //总学习时间 ms
                "sun":300, // 增加的阳光值
                "sunCost":60,  // 嗮太阳减少时间 minute
                "adSwitch" : true
            };
            return JSON.stringify(info);     
        }
    }
    public static showVideoAd(back){
        Log("Cocos 播放视频广告");
        // if (this.isAndrid && UserData.mainSwitch) {
        if (this.isAndroid && this.adSwitch) {
            Log("Cocos 播放视频广告 开启!");
            jsb.reflection.callStaticMethod(this.androidJavaPath, "showVideo", "()V");
            cc.showVideoCallback = (key)=>{
                if (key){
                    Log('成功播放视频,加钱加钱')
                    back();
                }
            }
        }
        if (!this.isAndroid){
            back();
        }
    }

    public static loadUiComplete(){
        if(this.isAndroid){
            Log('游戏加载完成 发送回调')
            jsb.reflection.callStaticMethod(this.androidJavaPath, "loadUiSuccess", "()V");
        }
    }

    public static upDateComplete(){
        if(this.isAndroid){
            jsb.reflection.callStaticMethod(this.androidJavaPath, "updateComplete", "()V");
        }
    }

    public static showYhxy(){
        if(this.isAndroid){
            jsb.reflection.callStaticMethod(this.androidJavaPath, "showYhxy", "()V");
        }
    }

    public static startRecord(path){
        if(this.isAndroid){
            jsb.reflection.callStaticMethod(this.androidJavaPath, "startRecord", "(Ljava/lang/String;)V",path);
        }
    }
    
    public static stopRecord(){
        if(this.isAndroid){
            jsb.reflection.callStaticMethod(this.androidJavaPath, "stopRecord", "()V");
        }
    }

    public static getAndroidBasePath(){
        if(this.isAndroid){
            let path = jsb.reflection.callStaticMethod(this.androidJavaPath, "getBaseRecordPath", "()Ljava/lang/String;");
            return path;
        }
        else{
            let path = '你傻逼吗这是安卓环境吗还拿地址?';
            cc.error(path);
            return path;
        }
    }

    public static playAndroidMusic(path:string){
        Log('播放安卓音乐')
        if(this.isAndroid){
            jsb.reflection.callStaticMethod(this.androidJavaPath, "playMusic","(Ljava/lang/String;)V",path);
        }
    }

    public static stopAndroidMusic(){
        Log('停止安卓音乐')
        if(this.isAndroid){
            jsb.reflection.callStaticMethod(this.androidJavaPath, "stopMusic","()V");
        }
    }


    public static listenAndroidBack() {
        this.setAndroidBackListence(function(){

                    // PromptManage.addExitDialog()
                cc.find('Canvas/ExitDialog').active = true;
            
        },null,function(){
            // PromptManage.addExitDialog()
            cc.find('Canvas/ExitDialog').active = true;
            
            return true;
        })
    }
    
  /************************************************** 打包Android 必备 ************************************************************* */
    
    /**
     * 每个场景中调用setAndroidBackListence() 监听Android端返回按钮
     * 
     * 需要Android端CocosHelp配合，CocosHelp中必须存在goBack()方法，goBack返回true则表示Android端拦截了本次事件，一般默认返回false
     * 本方法适配了特殊机型导致的cc监听不到的情况，需要在AppActivity中的onBackPressed（）方法下回调ackFunction()
     * 如下：
        @Override
        public void onBackPressed() {
            SDKWrapper.getInstance().onBackPressed();
            Log.i("CocosHelp", "点击返回按钮");
            CocosHelp.onBackPressed();
            // super.onBackPressed();
        }

        *** CocosHelp必备方法：

        public class CocosHelp {

            public static void onBackPressed(){
                Cocos2dxHelper.runOnGLThread(new Runnable() {
                @Override
                public void run() {
                    Cocos2dxJavascriptJavaBridge.evalString("JsbUtil.backFunction()");
                }
                });
            }

            public static boolean goBack(){
                return false;
            }

        }

     * 
     * @param callback Android原生不拦截则回调（如无特殊情况，可在此执行退出弹窗）
     * @param targrt 
     * @param interceptorCallback 本地拦截器 返回true则为拦截后续操作
     */
    public static setAndroidBackListence(callback, targrt?, interceptorCallback?){
        this.callback = callback;
        this.targrt = targrt;
        this.interceptorCallback = interceptorCallback;
        var self = this;
        Log("注册了返回按钮");
        cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP);
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, function(event){
            Log("用户点击了返回按钮", event.keyCode + " : " + cc.macro.KEY.back);
            // 8 键盘的回退键
            if(event.keyCode == cc.macro.KEY.back || event.keyCode == 8){
                self.backFunction();
            }
        },targrt);
    }

    public static setInterceptor2Callback(interceptor2Callback){
        this.interceptor2Callback = interceptor2Callback;
    }

    public static backFunction() {
        if (this.interceptor2Callback) {
            var interceptor = this.interceptor2Callback();
            if (interceptor && interceptor == true) {
                Log("Cocos 二级拦截器 拦截了返回事件");
                return;
            }
        }

        if (this.interceptorCallback) {
            var cancel = this.interceptorCallback();
            if (cancel && cancel == true) {
                Log("Cocos拦截了返回事件");
                return;
            }
        }

        if (this.isAndroid) {
            var result = jsb.reflection.callStaticMethod(this.androidJavaPath, "goBack", "()Z");
        }

        if (result && result == true) {
            Log("Andorid拦截了返回事件");
        } else if (this.callback) {
            this.callback();
        }
    }
    public static showLoading(key){

    }
    
}
window["JsbUtil"] = JsbUtil;